"""
===========================
Mouse move and click events
===========================

An example of how to interact with the plotting canvas by connecting to move
and click events.
"""

from matplotlib.backend_bases import MouseButton
import matplotlib.pyplot as plt
import numpy as np

t = np.arange(0.0, 1.0, 0.01)
s = np.sin(2 * np.pi * t)
fig, ax = plt.subplots()
ax.plot(t, s)


def on_move(event):
    # get the x and y pixel coords
    global binding_id,st_fig,st_loc,arrow
    x, y = event.xdata, event.ydata
    dx,dy = x-st_loc[0],y-st_loc[1]
    # if event.inaxes:
    if (arrow): arrow.remove()
    arrow = ax.arrow(st_loc[0],st_loc[1],dx,dy)
    plt.draw()

st_fig = None
st_loc = None
arrow = None
binding_id = None

def on_click(event):
    global binding_id,st_fig,st_loc
    if event.button is MouseButton.LEFT:
        if (binding_id == None):
            if (st_fig):  st_fig.remove()
            st_fig = ax.scatter(event.xdata, event.ydata,s=1,c='red')
            st_loc = (event.xdata, event.ydata)
        # print('disconnecting callback')
        # plt.disconnect(binding_id)
            binding_id = plt.connect('motion_notify_event', on_move)
        else:
            plt.disconnect(binding_id)
    plt.draw()

# binding_id = plt.connect('motion_notify_event', on_move)
plt.connect('button_press_event', on_click)

plt.show()
